using BanZuiCloudControlAgent.Utils.Database.Repositories;
using BanZuiCloudControlAgent.Utils.Logging;
using Microsoft.Win32;
using System;
using System.IO;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;

namespace BanZuiCloudControlAgent.Core.Startup
{
    /// <summary>
    /// 启动管理器，负责应用程序启动时的初始化工作
    /// </summary>
    public class StartupManager
    {
        private const string RegistryKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
        private const string AppName = "BanZuiCloudControlAgent";
        private static readonly Logger _logger = LogManager.GetLogger(nameof(StartupManager));
        private static System.Threading.Timer _cleanupTimer;
        
        /// <summary>
        /// 初始化应用程序
        /// </summary>
        public static void Initialize()
        {
            try
            {
                _logger.Info("开始初始化应用程序");
                
                // 延迟初始化数据库清理定时器，避免在应用程序启动阶段就访问数据库
                Task.Delay(TimeSpan.FromMinutes(1)).ContinueWith(_ => InitializeCleanupTimer());
                
                _logger.Info("应用程序初始化完成");
            }
            catch (Exception ex)
            {
                _logger.Error("应用程序初始化失败", ex);
            }
        }
        
        /// <summary>
        /// 初始化数据库清理定时器
        /// </summary>
        private static void InitializeCleanupTimer()
        {
            try
            {
                _logger.Info("初始化数据库清理定时器");
                
                // 每天凌晨3点执行清理
                var now = DateTime.Now;
                var nextRun = new DateTime(now.Year, now.Month, now.Day, 3, 0, 0);
                if (now > nextRun)
                {
                    nextRun = nextRun.AddDays(1);
                }
                
                var timeToNextRun = nextRun - now;
                
                _cleanupTimer = new System.Threading.Timer(async state => await CleanupDatabaseAsync(),
                    null,
                    timeToNextRun,
                    TimeSpan.FromDays(1));
                
                _logger.Info($"数据库清理定时器已启动，下次执行时间: {nextRun}");
            }
            catch (Exception ex)
            {
                _logger.Error("初始化数据库清理定时器失败", ex);
            }
        }
        
        /// <summary>
        /// 清理数据库
        /// </summary>
        private static async Task CleanupDatabaseAsync()
        {
            try
            {
                _logger.Info("开始清理数据库");
                
                try
                {
                    var repository = new MqttMessageRepository();
                    int cleanedCount = await repository.CleanupOldMessagesAsync();
                    
                    _logger.Info($"数据库清理完成，共清理 {cleanedCount} 条消息");
                }
                catch (Exception dbEx)
                {
                    _logger.Error("执行数据库清理操作失败", dbEx);
                    // 不再向上抛出异常，避免影响定时器
                }
            }
            catch (Exception ex)
            {
                _logger.Error("清理数据库失败", ex);
                // 不再向上抛出异常，避免影响定时器
            }
        }

        /// <summary>
        /// 配置应用程序是否开机自启动
        /// </summary>
        /// <param name="enable">是否启用开机自启动</param>
        public void ConfigureAutoStart(bool enable)
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath, true))
                {
                    if (key != null)
                    {
                        if (enable)
                        {
                            string appPath = Application.ExecutablePath;
                            key.SetValue(AppName, appPath);
                            _logger?.Info($"已设置开机自启动: {appPath}");
                        }
                        else
                        {
                            if (key.GetValue(AppName) != null)
                            {
                                key.DeleteValue(AppName);
                                _logger?.Info("已取消开机自启动");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger?.Error($"配置开机自启动失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 检查应用程序是否设置为开机自启动
        /// </summary>
        /// <returns>如果设置了开机自启动则返回true，否则返回false</returns>
        public bool IsAutoStartEnabled()
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath))
                {
                    if (key != null)
                    {
                        return key.GetValue(AppName) != null;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger?.Error($"检查开机自启动状态失败: {ex.Message}", ex);
            }
            
            return false;
        }

        /// <summary>
        /// 启动应用程序的各项服务
        /// </summary>
        public void Start()
        {
            try
            {
                _logger?.Info("正在启动应用程序服务...");
                // 在这里可以添加应用程序启动时需要初始化的各项服务
                
                _logger?.Info("应用程序服务启动完成");
            }
            catch (Exception ex)
            {
                _logger?.Error($"启动应用程序服务失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 停止应用程序的各项服务
        /// </summary>
        public void Stop()
        {
            try
            {
                _logger?.Info("正在停止应用程序服务...");
                // 在这里可以添加应用程序关闭时需要清理的各项服务
                
                _logger?.Info("应用程序服务已停止");
            }
            catch (Exception ex)
            {
                _logger?.Error($"停止应用程序服务失败: {ex.Message}", ex);
            }
        }
    }
} 